package com.example.portablefortheelderlybackground.sevice.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.portablefortheelderlybackground.common.StringCommon;
import com.example.portablefortheelderlybackground.common.redis.redisKey;
import com.example.portablefortheelderlybackground.mapper.sportMapper;
import com.example.portablefortheelderlybackground.pojo.sport.sport;
import com.example.portablefortheelderlybackground.sevice.sportService;
import com.example.portablefortheelderlybackground.utils.Response;
import com.example.portablefortheelderlybackground.utils.SportSingleton;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

import static com.example.portablefortheelderlybackground.Enum.Message.ReturnMessageEnum.*;

@Service
@Slf4j
@Transactional(timeout = 3)
public class sportServiceImpl extends ServiceImpl<sportMapper, sport> implements sportService {
    private final
    RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public sportServiceImpl(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public Response<Page<sport>> getSportList(Integer pages, Integer pageSize, String type) {
        //判读redis是否存在缓存
        Page<sport> redisSportPage = (Page<sport>) redisTemplate.opsForValue().get(redisKey.sportQueryKey + type);
        if (!ObjectUtils.isEmpty(redisSportPage)) {
            return Response.success(redisSportPage, SUCCESS.getCode(), SUCCESS.getMessage());
        }
        //查询所有的sport运动类
        Page<sport> page = new Page<>(pages, pageSize);
        LambdaQueryWrapper<sport> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(type != null, sport::getType, type);
        //按照创建的时间进行排序
        queryWrapper.orderByAsc(sport::getCreateTime);
        baseMapper.selectPage(page, queryWrapper);
        //查询成功，将数据放到redis缓存中去
        //如果list为空,则返回系统繁忙
        if (!ObjectUtils.isEmpty(page.getRecords())) {
            redisTemplate.opsForValue().set(redisKey.sportQueryKey + type, page, StringCommon.TimeOut, TimeUnit.HOURS);
        }
        return page.getRecords() == null ? Response.error(page, NOT_FOUNT.getCode(), NOT_FOUNT.getMessage()) : Response.success(page, SUCCESS.getCode(), SUCCESS.getMessage());
    }

    @Override
    public Response<sport> getSportById(String id) {
        //查缓存
        sport redisSportById = (sport) redisTemplate.opsForValue().get(redisKey.sportKey + id);
        if (!ObjectUtils.isEmpty(redisSportById))
            return Response.success(redisSportById, SUCCESS.getCode(), SUCCESS.getMessage());
        sport sportById = baseMapper.selectById(id);
        //判断查询的dish为空，如果不为空，做redis缓存
        if (!ObjectUtils.isEmpty(sportById)) {
            redisTemplate.opsForValue().set(redisKey.sportKey + id, sportById, StringCommon.TimeOut, TimeUnit.HOURS);
        }
        return sportById == null ? Response.error(SportSingleton.getInstance(), NOT_FOUNT.getCode(), NOT_FOUNT.getMessage()) : Response.success(sportById, SUCCESS.getCode(), SUCCESS.getMessage());
    }

    @Override
    public Response<sport> updateSportById(sport updateSport) {
        LambdaQueryWrapper<sport> sportLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sportLambdaQueryWrapper.in(sport::getId, updateSport.getId());
        int updateFlag = baseMapper.updateById(updateSport);
        if (updateFlag > 0) {
            log.error("{},id为{}的dish修改失败!", LocalDateTime.now(), updateSport.getId());
            return Response.error(SportSingleton.getInstance(), SERVER_ERROR.getCode(), SERVER_ERROR.getMessage());
        }
        //清除redis中sport列表的缓存
        redisTemplate.opsForValue().getOperations().delete(redisKey.sportQueryKey + updateSport.getType());
        redisTemplate.opsForValue().getOperations().delete(redisKey.sportKey + updateSport.getId());
        //返回对应的数据
        return Response.success(updateSport, SAVE_SUCCESS.getCode(), SAVE_SUCCESS.getMessage());
    }

    @Override
    public Response<sport> saveSport(sport saveSport) {
        int saveFlag = baseMapper.insert(saveSport);
        if (saveFlag > 0) {
            log.info("{},成功保存一条dish数据,id为:{}", LocalDateTime.now(), saveSport.getId());
            //清除redis中sport的缓存
            redisTemplate.opsForValue().getOperations().delete(redisKey.sportQueryKey + saveSport.getType());
            return Response.success(saveSport, SAVE_SUCCESS.getCode(), SAVE_SUCCESS.getMessage());
        }
        log.warn("数据不为空，但数据保存失败-{}", LocalDateTime.now());
        return Response.error(null, SERVER_ERROR.getCode(), SERVER_ERROR.getMessage());
    }

    @Override
    public Response deleteSport(String id) {
        //删除之前到数据库查询对应的实体信息
        sport deleteSport = baseMapper.selectById(id);
        int removeFlag = baseMapper.deleteById(id);
        if (removeFlag > 0) {
            //清除对应sportList缓存
            redisTemplate.opsForValue().getOperations().delete(redisKey.sportQueryKey + deleteSport.getType());
            //清除相对应的redis缓存,并清楚dishUser表相关连的数据
            redisTemplate.opsForValue().getOperations().delete(redisKey.sportKey + id);
            log.info("删除成功!-{}", LocalDateTime.now());
            return Response.success(DELETE_SUCCESS.getCode(), DELETE_SUCCESS.getMessage());
        }
        log.info("删除失败!-{}", LocalDateTime.now());
        return Response.error(SERVER_ERROR.getCode(), SAVE_ERROR.getMessage());
    }
}
